import { defineStore } from 'pinia'
import { ref } from 'vue'
import Taro from '@tarojs/taro'

export interface UserInfo {
  id?: string
  nickname?: string
  avatar?: string
  phone?: string
  email?: string
  wechatInfo?: any // 微信用户信息
  registerTime?: number // 注册时间
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo>({})
  const isLoggedIn = ref(false)

  // 初始化用户信息
  const initUserInfo = () => {
    try {
      const savedUserInfo = Taro.getStorageSync('user_info')
      if (savedUserInfo) {
        userInfo.value = savedUserInfo
        isLoggedIn.value = true
      }
    } catch (error) {
      console.error('初始化用户信息失败:', error)
    }
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = { ...userInfo.value, ...info, registerTime: info.registerTime || Date.now() }
    isLoggedIn.value = true
    
    try {
      Taro.setStorageSync('user_info', userInfo.value)
    } catch (error) {
      console.error('保存用户信息失败:', error)
    }
  }

  // 注册用户
  const register = async (registerData: { nickname: string; avatar: string; wechatInfo?: any }) => {
    try {
      // 这里应该调用实际的注册API
      // const response = await api.register(registerData)
      
      // 构造用户信息
      const newUserInfo: UserInfo = {
        id: 'user_' + Date.now(), // 实际项目中应该由服务器生成
        nickname: registerData.nickname,
        avatar: registerData.avatar,
        wechatInfo: registerData.wechatInfo,
        registerTime: Date.now()
      }
      
      setUserInfo(newUserInfo)
      return newUserInfo
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    isLoggedIn.value = false
    
    try {
      Taro.removeStorageSync('user_info')
    } catch (error) {
      console.error('清除用户信息失败:', error)
    }
  }

  // 登录
  const login = async (loginData: any) => {
    try {
      // 这里应该调用实际的登录API
      // const response = await api.login(loginData)
      
      // 模拟登录成功
      const mockUserInfo: UserInfo = {
        id: '1',
        nickname: '用户' + Math.floor(Math.random() * 1000),
        avatar: 'https://via.placeholder.com/100x100',
        phone: loginData.phone || '',
        email: loginData.email || ''
      }
      
      setUserInfo(mockUserInfo)
      return mockUserInfo
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 登出
  const logout = () => {
    clearUserInfo()
  }

  return {
    userInfo,
    isLoggedIn,
    initUserInfo,
    setUserInfo,
    clearUserInfo,
    login,
    logout,
    register
  }
}) 